package com.wang.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.wang.annotation.Service;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by wangq on 2021/7/11.
 */
@Service
public class ConnectionUtils {
    private final ThreadLocal<Connection> threadLocalConnection = new ThreadLocal<>();

    /**
     * 获取当前线程的Connection链接
     *
     * @return 链接
     */
    public Connection getCurrentThreadConn() throws SQLException {
        // 查看当前线程中是否有Connection链接
        if (this.threadLocalConnection.get() == null) {
            DruidDataSource druidDataSource = DataSourceUtil.getInstance();
            this.threadLocalConnection.set(druidDataSource.getConnection());
        }
        return this.threadLocalConnection.get();
    }
}
